package com.yeu.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.yeu.model.User;
import com.yeu.util.ConnectionPool;

public class LoginAction extends ActionSupport implements ModelDriven<User>,SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Map<String, String> result=new HashMap<String, String>();
	private User user=new User();
	private String loginType;
	private Map<String,Object> session;
	private String rd;
	public void setRd(String rd) {
		this.rd = rd;
	}

	public void setLoginType(String loginType) {
		this.loginType = loginType;
	}

	public Map<String, String> getResult() {
		return result;
	}

	@Override
	public User getModel() {
		return this.user;
	}
	
	@Override
	public void setSession(Map<String, Object> session) {
		this.session=session;
	}
	
	@Override
	public String execute() throws Exception {
		this.login();
		return SUCCESS;
	}
	
	public String out() throws Exception {
		session.clear();
		return SUCCESS;
	}
	
	private void login(){
		String sql;
		if(loginType.equals("0")){
			sql="select * from USERTABLE where USERID=? and PASSWORD=?";
		}
		else{
			sql="select * from EVENT where EVENTID=? and REPORTERNAME=?";
		}
		List<Map<String, String>> resultList=ConnectionPool.executeQuery(sql, user.getUserId(),user.getPassword());
		if(user.getVerify().equalsIgnoreCase((String)session.get("verify"))){
			if(resultList.size()==1){
				user.setRoleId(resultList.get(0).get("ROLEID"));
				if(loginType.equals("0")){
					session.put("roleId", user.getRoleId());
					session.put("userName", resultList.get(0).get("USERNAME"));
					session.put("userId", resultList.get(0).get("USERID"));
					session.put("departmentId", resultList.get(0).get("DEPARTMENTID"));
				}
				else{
					session.put("roleId", "9999");
					session.put("userName", user.getPassword());
					session.put("eventId", user.getUserId());
				}
				result.put("RESULT", "true");
			}
			else{
				result.put("RESULT", "false");
			}
		}
		else{
			result.put("RESULT", "��֤�����");
		}
	}
	
	//定时十分钟请求服务器，防止session过期
	public String sessionExpire(){
			result.put("RESULT", "true");
			return SUCCESS;
	}
}
